const router = require('koa-router')()
const CardNumberModel = require('../models/cardNumber')


router.prefix('/api')

//卡号添加
router.post('/addCardNumber',async (ctx)=>{
    ctx.status = 200

    let data = ctx.request.body
    let {card_header,card_type,affiliation} = data

    let cardData = await CardNumberModel.find({})

    let id = 1
    if(cardData.length != 0){
        id = cardData[cardData.length-1].id+1
    }

    await CardNumberModel.create({id,card_header,card_type,affiliation})

    ctx.body = {
        code:200,
        msg:"数据添加成功"
    }
})

//卡号查找
router.post('/findCardNumber',async (ctx)=>{
    ctx.status = 200

    let data = ctx.request.body
    let {card_header,affiliation} = data

    let cardData = []

    if(card_header && !affiliation){
        cardData = await CardNumberModel.find({card_header},{_id:0})
    }else if(!card_header && affiliation){
        cardData = await CardNumberModel.find({affiliation},{_id:0})
    }else if(card_header && affiliation){
        cardData = await CardNumberModel.find({card_header,affiliation},{_id:0})
    }else {

    }

    ctx.body = {
        code:200,
        data:cardData
    }

})

//卡号修改
router.post('/updateCardNumber',async (ctx)=>{
    ctx.status = 200

    let data = ctx.request.body
    let {id,card_header} = data

    let res = await CardNumberModel.findOneAndUpdate({id}, {$set: {card_header}})

    if(res != null){
        ctx.body = {
            code:200,
            msg:"卡号头部更新成功"
        }
    }else {
        ctx.body = {
            code:200,
            msg:"更新失败，未找到数据"
        }
    }

})

//卡号删除
router.post('/deleteCardNumber',async (ctx)=>{
    ctx.status = 200

    let data = ctx.request.body
    let {id} = data

    let res = await CardNumberModel.findOneAndDelete({id})

    if(res != null){
        ctx.body = {
            code:200,
            msg:"删除成功"
        }
    }else {
        ctx.body = {
            code:200,
            msg:"删除失败，未找到相关数据"
        }
    }
})

router.get('/getCardNumber',async (ctx)=>{
    ctx.status = 200

    let res = await CardNumberModel.find({})

    ctx.body = {
        code:200,
        data:res
    }
})




module.exports = router
